/**
 * 自定义404错误类
 */

class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
  }
}

function success(res, message, data, code = 200) {
  res.status(code).json({
    status: '0000',
    message,
    data,
  });
}

function failure(res, err) {
  console.log(err.name);
  if (err.name === 'SequelizeValidationError') {
    const error = err.errors.map((e) => e.message);
    res.status(400).json({
      status: '9999',
      message: '请求参数错误',
      error: error,
    });
  } else if (err.name == 'NotFoundError') {
    res.status(404).json({
      status: '9999',
      message: '资源不存在',
      error: [err.message],
    });
  } else {
    res.status(500).json({
      status: '9999',
      message: '服务器错误',
      error: [err.message],
    });
  }
}

module.exports = {
  NotFoundError,
  success,
  failure,
};
